import os
from typing import Dict, Optional

import pandas as pd
import requests
from modelscope_agent.constants import ApiNames
from modelscope_agent.tools.base import BaseTool, register_tool
from modelscope_agent.utils.utils import get_api_key


@register_tool('amap_weather')
class AMAPWeather(BaseTool):
    description = '获取对应城市的天气数据'
    name = 'amap_weather'
    parameters: list = [{
        'name': 'location',
        'type': 'string',
        'description': '城市/区具体名称，如`北京市海淀区`请描述为`海淀区`',
        'required': True
    }]

    def __init__(self, cfg: Optional[Dict] = None):
        super().__init__(cfg)

        # remote call
        self.url = 'https://restapi.amap.com/v3/weather/weatherInfo?city={city}&key={key}'
        self.city_df = pd.read_excel(
            'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/agent/AMap_adcode_citycode.xlsx'
        )

        self.api_key = self.cfg.get(
            ApiNames.amap_api_key.name,
            os.environ.get(ApiNames.amap_api_key.value, ''))

    def get_city_adcode(self, city_name):
        filtered_df = self.city_df[self.city_df['中文名'] == city_name]
        if len(filtered_df['adcode'].values) == 0:
            raise ValueError(
                f'location {city_name} not found, availables are {self.city_df["中文名"]}'
            )
        else:
            return filtered_df['adcode'].values[0]

    def call(self, params: str, **kwargs) -> str:
        params = self._verify_args(params)
        if isinstance(params, str):
            return 'Parameter Error'
        try:
            self.api_key = get_api_key(ApiNames.amap_api_key, self.api_key,
                                       **kwargs)
        except AssertionError:
            raise ValueError(
                'weather api token must be acquired through ',
                'https://lbs.amap.com/api/webservice/guide/create-project/get-key and set by AMAP_TOKEN'
            )
        location = params['location']
        response = requests.get(
            self.url.format(
                city=self.get_city_adcode(location), key=self.api_key))
        data = response.json()
        if data['status'] == '0':
            raise RuntimeError(data)
        else:
            weather = data['lives'][0]['weather']
            temperature = data['lives'][0]['temperature']
            return f'{location}的天气是{weather}温度是{temperature}度。'
